package com.bootdo.system.service.impl;

import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.R;
import com.bootdo.system.dao.AppVersionDao;
import com.bootdo.system.domain.AppVersionDO;
import com.bootdo.system.service.AppVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AppVersionServiceImpl implements AppVersionService {

    @Value("${app.packageAddress}")
    private String packageAddress;
    @Value("${app.downloadAddress}")
    private String downloadAddress;

    @Autowired
    private AppVersionDao appVersionMapper;

    @Override
    public AppVersionDO get(Long appId){
        return appVersionMapper.get(appId);
    }

    @Override
    public List<AppVersionDO> list(Map<String, Object> map){
        return appVersionMapper.list(map);
    }

    @Override
    public int count(Map<String, Object> map){
        return appVersionMapper.count(map);
    }



    @Override
    public R uploadAppPackage(MultipartFile appPackage,String versionNumber,String sign,String mandatoryUpdate) throws Exception {
        if(!appPackage.isEmpty()){
            String appPackageName = appPackage.getOriginalFilename();
            String fileSuffix = appPackageName.substring(appPackageName.lastIndexOf(".") + 1).toLowerCase();
            if("apk".equals(fileSuffix)){
                String filePath = "/APP" + "/" + DateUtils.toHyphenatedYyyyMmDdHh(new Date())+ "/"+ appPackageName;
                String path = packageAddress + filePath;
                File app = new File(path);
                if(!app.getParentFile().exists()){
                    app.getParentFile().mkdirs();
                }
                appPackage.transferTo(app);

                AppVersionDO appVersion = new AppVersionDO();
                appVersion.setVersionNumber(versionNumber);
                appVersion.setSign(sign);
                appVersion.setMandatoryUpdate(mandatoryUpdate);

                String downloadPath = downloadAddress + filePath;
                appVersion.setDownloadPath(downloadPath);
                appVersion.setGmtCreate(new Date());
                int i = appVersionMapper.save(appVersion);
                if(i != 1){
                    return R.error(-1,"保存版本信息失败");
                }

                return R.ok();
            }else {
                return R.error(-1,"上传文件非apk");
            }
        }else{
            return R.error(-1,"上传文件为空");
        }

    }

    @Override
    public AppVersionDO downloadAppPackage() {
        AppVersionDO appVersion = appVersionMapper.getNew();
        return appVersion;
    }


}
